package io.lckgroup.modules.lck.utils.order;

import org.apache.commons.lang.StringUtils;
import org.bouncycastle.crypto.digests.SM3Digest;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 通过国米签名
 *
 * @author Administrator
 */
public class SMSaltSigner {

    /**
     * 密钥长度{@value}(按byte数组计算，转成base64后不一样)
     */
    private static final int KEY_LEN = 32;

    public String genKey() {
        return Base64.getEncoder().encodeToString(StringUtil.genRandomByte(KEY_LEN));
    }

    public String sign(ISignBlock signBlock, String key) {
        String input = signBlock.getSignBlock();
        String dataWithSalt = input + key;
        byte[] srcByte = dataWithSalt.getBytes(StandardCharsets.UTF_8);
        byte[] md = new byte[32];
        SM3Digest sm3 = new SM3Digest();
        sm3.update(srcByte, 0, srcByte.length);
        sm3.doFinal(md, 0);
        String ret = Base64.getEncoder().encodeToString(md);
        return ret;
    }

    public boolean verify(ISignBlock signBlock, String sign, String key) {
        String sign2 = sign(signBlock, key);
        if (StringUtils.isEmpty(sign) || StringUtils.isBlank(sign)) {
            return false;
        } else {
            return sign2.equals(sign);
        }
    }

    /**
     * sm4加密
     *
     * @param secretKey 秘钥
     * @param plainText 待加密报文
     * @return 已加密报文
     */
    public String encryptData(String secretKey, String plainText) {
        SM4Utils sm4 = new SM4Utils();
        sm4.secretKey = secretKey;
        sm4.hexString = true;
        String cipherText = sm4.encryptData_ECB(plainText);
        return cipherText;
    }

    /**
     * sm4解密
     *
     * @param secretKey  秘钥
     * @param cipherText 待解密报文
     * @return 已解密报文
     */
    public String decryptData(String secretKey, String cipherText) {
        SM4Utils sm4 = new SM4Utils();
        sm4.secretKey = secretKey;
        sm4.hexString = true;
        String plainText = sm4.decryptData_ECB(cipherText);
        return plainText;
    }

    /**
     * sm2解密
     *
     * @param secretKey  私钥
     * @param cipherText 待解密报文
     * @return 已解密报文
     */
    public String decryptSm2(String secretKey, String cipherText) {
        SM2Util sm2 = new SM2Util();
        String deData = sm2.decrypt(Utils.hexStringToBytes(cipherText), secretKey);
        return deData;
    }
}
